package com.mzy.javaapi.Jdk8;

import com.mzy.common.ApiResult;

import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/4/24 10:04
 * @Version 1.0
 */
public class orElseAndOrElseGet {
    /**
     * JDK1.8
     * Optional操作，orElse和orElseGet的区别和用途
     * @param args
     */
    public static void main(String[] args){
        String nullValue = null;
        String optional = Optional.ofNullable(nullValue).orElse("Su");
        System.out.println(optional);
        String optionalGet = Optional.ofNullable(nullValue).orElseGet(() -> "Xiao");
        System.out.println(optionalGet);
        String nonNullOptional = Optional.ofNullable("Susan").orElse("Su");
        System.out.println(nonNullOptional);
        String nonNullOptionalGet = Optional.ofNullable("Molly").orElseGet(() -> "Xiao");
        System.out.println(nonNullOptionalGet);

        ApiResult<Object> test = test();
        System.out.println(test.getTitle());
        System.out.println(Optional.ofNullable("xx").get());
    }

    /**
     * orElseGet 只有在Optional为空时，才会执行
     * @return
     */
    public static ApiResult<Object> test(){
//        Optional<String> msg = iptablesService.deleteIptables(id);
        return Optional.ofNullable("xx").map(s -> ApiResult.createBuilder().withTitle("WebConstant.DEL_ERROR").withDescribe("错误测试").buildError()).
                orElseGet(() -> ApiResult.createBuilder().withTitle("WebConstant.DEL_SUCCESS").buildOk());
    }
}
